﻿using LitJson;
using UnityEngine;
using UnityEngine.UI;

/*配置表格式
 {
    "onlyThisCodesCanDownloadPack":[],
    "onlyThisCodesCanHotfix":[],
    "versionCode":2,
    "versionName":"1.0",
    "url":"http://www.xxx.com",
    "desc":{
        "title":"有新的版本需要更新",
        "content":[
            "1.优化",
            "2.优化",
            "3.优化"
        ]
    }
}
*/

namespace CGF
{
    public class AppUpdate : MonoBehaviour
    {
        public VerticalLayoutGroup dialog;
        public Text content, textOR;
        public Button btnDownload, btnCopy;

        private string btnCopyDefaultText;

        /// <summary>
        /// 举例：当version.txt的canUpdateCode=5时，小于等于5的版本才可以更新（包括热更），所以提审的版本VersionCode大于5，就不会触发更新，
        /// 避免提审版和线上版本更新上的冲突
        /// </summary>
        public static bool canHotfix { private set; get; }

        private string packUrl;
        private float timer;

        private void Awake()
        {
            if (Application.platform != RuntimePlatform.Android || CGFConfig.Instance.isAppBundle)
            {
                btnDownload.GetComponentInChildren<Text>().text = "Install";
                textOR.gameObject.SetActive(false);
                btnCopy.gameObject.SetActive(false);
                dialog.padding.bottom = 250;
            }
        }

        public static async CTask CheckDownloadApp()
        {
            if (Application.isEditor)
            {
                canHotfix = true;
                return;
            }
            
            if (Define.IsWebGL && !Application.isEditor ||
                CGFConfig.Instance.ResStrategy == EResStrategy.StreamingAssetsOnly ||
                CGFConfig.Instance.ResStrategy == EResStrategy.Resources)
            {
                canHotfix = true;
                return;
            }

            CTask task = CTask.Create();
            string versionUrl = $"{CGFConfig.Instance.ResServer}/res/{CGFConfig.Instance.ReleaseArea.ToString()}/{CGFConfig.Instance.Tag}/{CGFConfig.Platform}";
            if (Application.isEditor)
            {
                versionUrl += "/apk";
            }
            if (Application.platform == RuntimePlatform.Android)
            {
                versionUrl += CGFConfig.Instance.isAppBundle ? "/aab" : "/apk";
            }
            else if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                versionUrl += "/ipa";
            }
            else if (Application.platform == RuntimePlatform.WebGLPlayer)
            {
                versionUrl += $"/res_v{CGFConfig.Instance.VersionCode}";
            }
            else
            {
                versionUrl += "/pc";
            }
            versionUrl += "/version.json";
            if (Application.isEditor) Debug.Log($"App版本信息: {versionUrl}");
            HttpRes res;
            while (true)
            {
                res = await HttpHelper.Get(versionUrl);
                if (!res.success)
                {
                    Debug.LogError($"请求App版本信息失败: {versionUrl} {res.text}");
                    await CTask.Wait(1);
                    Debug.Log($"再次尝试下载: {versionUrl}");
                }
                else
                {
                    break;
                }
            }
            JsonData json = JsonMapper.ToObject(res.text);
            JsonData data = null;
            if (json.Contains("formal"))
            {
                data = CGFConfig.Instance.ResServerType == EResServerType.FormalServer ? json["formal"] : json["test"];
            }
            else
            {
                data = json;
            }
            JsonData onlyThisCodesCanDownloadPack = data["onlyThisCodesCanDownloadPack"];
            JsonData onlyThisCodesCanHotfix = data["onlyThisCodesCanHotfix"];
            int remoteCode = (int)data["versionCode"];
            int localCode = AppHelper.GetAppVersionCode();
            if (onlyThisCodesCanHotfix == null || onlyThisCodesCanHotfix.Count == 0 || (int)onlyThisCodesCanHotfix[0] == -1)
            {
                canHotfix = true;
            }
            else
            {
                for (int i = 0; i < onlyThisCodesCanHotfix.Count; i++)
                {
                    if ((int)onlyThisCodesCanHotfix[i] == localCode)
                    {
                        canHotfix = true;
                        break;
                    }
                }
                if (!canHotfix)
                {
                    Debug.LogError($"App Version Code [{localCode}] 不在以下数组内，不予热更: {onlyThisCodesCanHotfix.ToJson()}");
                }
            }

            //判断是否能下载新包
            bool canDownloadPack = false;
            if (onlyThisCodesCanDownloadPack == null || onlyThisCodesCanDownloadPack.Count == 0 || (int)onlyThisCodesCanDownloadPack[0] == -1)
            {
                canDownloadPack = true;
            }
            else
            {
                for (int i = 0; i < onlyThisCodesCanDownloadPack.Count; i++)
                {
                    if ((int)onlyThisCodesCanDownloadPack[i] == localCode)
                    {
                        canDownloadPack = true;
                        break;
                    }
                }
                if (!canDownloadPack)
                {
                    Debug.Log($"App Version Code [{localCode}] 不在以下数组内，不予下载新包: {onlyThisCodesCanDownloadPack.ToJson()}");
                }
            }

            Debug.Log($"canDownloadPack: {canDownloadPack}");
            Debug.Log($"App版本信息: {localCode} == {remoteCode}");
            if (!canDownloadPack)
            {
                task.SetResult();
            }
            else
            {
                if (localCode == remoteCode)
                {
                    task.SetResult();
                }
                else
                {
                    MainLaunch.instance.ShowErrorText("Need to upgrade.");
                    PopupDialog(data);
                }
            }
            await task;
        }

        private static void PopupDialog(JsonData data)
        {
            AppUpdate appUpdate = GameObject.Instantiate(Resources.Load<AppUpdate>("AppUpdate"));
            appUpdate.SetContent(data);
        }

        private void Update()
        {
            if (timer > 0)
            {
                timer -= Time.deltaTime;
                if (timer <= 0)
                {
                    btnCopy.GetComponentInChildren<Text>().text = btnCopyDefaultText;
                }
            }
        }

        private void SetContent(JsonData data)
        {
            btnDownload.onClick.AddListener(() =>
            {
                Application.OpenURL(packUrl);
            });

            if (string.IsNullOrEmpty(btnCopyDefaultText))
            {
                btnCopyDefaultText = btnCopy.GetComponentInChildren<Text>().text;
            }
            btnCopy.onClick.AddListener(() =>
            {
                CopyAndPaste.Copy(packUrl);
                btnCopy.GetComponentInChildren<Text>().text = "Copied!";
                timer = 3;
            });

            string content = $"<size=40><b>{data["desc"]["title"]}</b></size> ({data["versionName"]})";
            JsonData contents = data["desc"]["content"];
            if (contents.Count > 0)
            {
                content += "\n";
            }
            for (int i = 0; i < contents.Count; i++)
            {
                content += $"\n{contents[i]}";
            }
            this.content.text = content;
            packUrl = data["url"].ToString();
        }
    }
}
